package com.wtpaint.udp.test1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * UDP提供者，用于提供服务
 * 优先启动
 */
public class UDPProvider {

    public static void main(String[] args) throws IOException {
        System.out.println("UDPProvider started.");
        //作为接收者，制定一个端口用于数据接收
        DatagramSocket ds = new DatagramSocket(20001);

        //构建接受实体
        final byte[] buf = new byte[512];
        DatagramPacket receivePack = new DatagramPacket(buf, buf.length);

        ds.receive(receivePack);

        //打印信息
        String ip = receivePack.getAddress().getHostAddress();
        int port = receivePack.getPort();
        int dataLen = receivePack.getLength();
        String data = new String(receivePack.getData(), 0, dataLen);
        System.out.println("UDPProvider receive form ip :" + ip + " port:" + port + " data:" + data);

        //构建回送数据
        String responseData = " dataLen :" + dataLen;
        //直接根据发送者的信息构建一份回送信息
        DatagramPacket resonsePack = new DatagramPacket(responseData.getBytes(),
                responseData.getBytes().length,
                receivePack.getAddress(),
                receivePack.getPort());
        //回送
        ds.send(resonsePack);

        //完成，关闭
        System.out.println("UDPProvider Complete.");
        ds.close();
    }
}
